package yns.springboot.guide.demo.controller.data.db;

import java.time.LocalDateTime;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import tools.jackson.databind.ObjectMapper;
import tools.jackson.databind.json.JsonMapper;
import yns.springboot.guide.demo.controller.BaseController;
import yns.springboot.guide.demo.entity.UserEntity;
import yns.springboot.guide.demo.service.jdbc.UserServiceJDBC;

@RestController
public class TestJDBCController extends BaseController {
	
	// http://localhost:8080/jdbc/select
	// http://localhost:8080/jdbc/add
	// http://localhost:8080/jdbc/delete
	// http://localhost:8080/jdbc/update
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	 
	@Autowired
	private UserServiceJDBC userServiceJDBC;
	
	@RequestMapping("/jdbc/select")
	public String testJDBCSelect() {
		logger.info(httpServletRequest.getRequestURI());
		
		List<UserEntity> userEntities = userServiceJDBC.getUser();

		ObjectMapper objectMapper = JsonMapper.builder().build();
		String result = objectMapper.writeValueAsString(userEntities);
		
//		ObjectMapper objectMapper = new ObjectMapper();
//		String result = "";
//		try {
//			result = objectMapper.writeValueAsString(userEntities);
//		} catch (JsonProcessingException e) {
//			e.printStackTrace();
//		}
		
		return result;
	}
	
	@RequestMapping("/jdbc/add")
	public String testJDBCAdd() {
		logger.info(httpServletRequest.getRequestURI());
		
		UserEntity userEntity = new UserEntity();
		userEntity.setName("test");
		userEntity.setAge(34);
		userEntity.setSex(1);
		userEntity.setDescribe("master jdbc "  + LocalDateTime.now());
		
		userServiceJDBC.addUser(userEntity);
		
		String result = "add";
		
		return result ;
	}
	
	@RequestMapping("/jdbc/delete")
	public String testJDBCDelete() {
		logger.info(httpServletRequest.getRequestURI());
		
		userServiceJDBC.deleteUser(0);
		
		String result = "delete";
		
		return result ;
	}
	
	@RequestMapping("/jdbc/update")
	public String testJDBCUpdate() {
		logger.info(httpServletRequest.getRequestURI());
		
		UserEntity userEntity = userServiceJDBC.getUser().get(0);
		userEntity.setDescribe("master jdbc update : " + LocalDateTime.now());
		
		userServiceJDBC.updateUser(userEntity);
		
		String result = "update id :" + userEntity.getId();
		
		return result ;
	}

}
